// src/Mine/Mutualfollowing.tsx
import { useState, useEffect } from 'react';
import { Modal, List, Avatar, Typography, Spin, message, Button } from 'antd';
import { UserOutlined, PlusOutlined, CheckOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';

const { Text } = Typography;

interface User {
  id: number;
  username: string;
  nickname: string;
  avatar?: string;
  bio?: string;
  isFollowing?: boolean;
}

interface FollowRelation {
  followerId: number;
  followeeId: number;
  createdAt: string;
}

interface MutualFollowingProps {
  visible: boolean;
  onClose: () => void;
  userId: number;
  isCurrentUser?: boolean;
  onFollowChange?: () => void; // 添加这个属性
}

function Mutualfollowing({ 
  visible, 
  onClose, 
  userId, 
  isCurrentUser = true,
  onFollowChange // 添加这个属性
}: MutualFollowingProps) {
  const navigate = useNavigate();
  const [mutualFollows, setMutualFollows] = useState<User[]>([]);
  const [mutualCount, setMutualCount] = useState<number>(0);
  const [loading, setLoading] = useState(false);
  const [followLoading, setFollowLoading] = useState<number | null>(null);

  // 获取用户详细信息
  const fetchUserDetails = async (userId: number): Promise<User | null> => {
    try {
      const token = localStorage.getItem('token');
      if (!token) return null;

      const endpoints = [
        `/api/users/${userId}`,
        `/api/users/search?uid=${userId}`,
        `/api/user/${userId}/profile`
      ];

      for (const endpoint of endpoints) {
        try {
          const response = await fetch(endpoint, {
            method: 'GET',
            headers: { 
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json'
            },
          });

          if (response.ok) {
            const userData = await response.json();
            
            const actualData = Array.isArray(userData) ? userData[0] : userData;
            
            if (actualData) {
              return {
                id: actualData.id || actualData.userId || userId,
                username: actualData.username || actualData.account || `user${userId}`,
                nickname: actualData.nickname || actualData.name || actualData.username || `用户${userId}`,
                avatar: actualData.avatar || actualData.avatarUrl,
                bio: actualData.bio || actualData.description || actualData.signature
              };
            }
          }
        } catch (error) {
          console.warn(`接口 ${endpoint} 失败:`, error);
          continue;
        }
      }

      return {
        id: userId,
        username: `user${userId}`,
        nickname: `用户${userId}`,
        bio: '该用户信息暂不可用'
      };
    } catch (error) {
      console.error('获取用户详情失败:', error);
      return {
        id: userId,
        username: `user${userId}`,
        nickname: `用户${userId}`,
        bio: '网络错误，用户信息获取失败'
      };
    }
  };

  // 检查关注状态
  const checkFollowingStatus = async (targetUserId: number): Promise<boolean> => {
    try {
      const token = localStorage.getItem('token');
      const currentUserId = localStorage.getItem('userId');
      
      if (!token || !currentUserId) return false;

      const response = await fetch(`/api/userfollows/check?followerId=${currentUserId}&followeeId=${targetUserId}`, {
        method: 'GET',
        headers: { 
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
      });

      if (response.ok) {
        const result = await response.json();
        return result.isFollowing || false;
      }
    } catch (error) {
      console.error('检查关注状态失败:', error);
    }
    return false;
  };

  // 关注/取消关注操作
  const handleFollowAction = async (user: User, index: number) => {
    if (!user.id) return;

    setFollowLoading(user.id);
    try {
      const token = localStorage.getItem('token');
      const currentUserId = localStorage.getItem('userId');
      
      if (!token || !currentUserId) {
        message.warning('请先登录');
        return;
      }

      const isCurrentlyFollowing = mutualFollows[index].isFollowing;

      if (isCurrentlyFollowing) {
        // 取消关注
        const response = await fetch(`/api/userfollows/${currentUserId}/${user.id}`, {
          method: 'DELETE',
          headers: { 
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
        });

        if (response.ok) {
          const updatedMutualFollows = [...mutualFollows];
          updatedMutualFollows[index].isFollowing = false;
          setMutualFollows(updatedMutualFollows);
          
          // 调用回调通知父组件
          if (onFollowChange) {
            onFollowChange();
          }
          message.success('已取消关注');
        } else {
          message.error('取消关注失败');
        }
      } else {
        // 关注
        const response = await fetch(`/api/userfollows`, {
          method: 'POST',
          headers: { 
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            followerId: parseInt(currentUserId),
            followeeId: user.id
          }),
        });

        if (response.ok) {
          const updatedMutualFollows = [...mutualFollows];
          updatedMutualFollows[index].isFollowing = true;
          setMutualFollows(updatedMutualFollows);
          
          // 调用回调通知父组件
          if (onFollowChange) {
            onFollowChange();
          }
          message.success('关注成功');
        } else {
          message.error('关注失败');
        }
      }
    } catch (error) {
      message.error('操作失败');
      console.error('关注操作异常:', error);
    } finally {
      setFollowLoading(null);
    }
  };

  const fetchMutualFollows = async () => {
    if (!userId) return;
    
    setLoading(true);
    try {
      const token = localStorage.getItem('token');
      
      // 获取关注列表
      const followeesResponse = await fetch(`/api/userfollows/follower/${userId}/followees`, {
        method: 'GET',
        headers: { 
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
      });

      // 获取粉丝列表
      const followersResponse = await fetch(`/api/userfollows/followee/${userId}/followers`, {
        method: 'GET',
        headers: { 
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
      });

      if (followeesResponse.ok && followersResponse.ok) {
        const followees: FollowRelation[] = await followeesResponse.json();
        const followers: FollowRelation[] = await followersResponse.json();
        
        // 找出互相关注的用户
        const followeeIds = new Set(followees.map((item: FollowRelation) => item.followeeId));
        const followerIds = new Set(followers.map((item: FollowRelation) => item.followerId));
        
        const mutualUserIds: number[] = [...followeeIds].filter((id): id is number => 
          followerIds.has(id as number)
        );
        setMutualCount(mutualUserIds.length);
        
        // 获取互关用户的详细信息
        const userDetailsPromises = mutualUserIds.map((id: number) => fetchUserDetails(id));
        const userDetails = await Promise.all(userDetailsPromises);
        
        // 检查每个用户的关注状态
        const usersWithFollowStatus = await Promise.all(
          userDetails.filter((user): user is User => user !== null).map(async (user) => {
            if (isCurrentUser) {
              return { ...user, isFollowing: true };
            } else {
              const isFollowing = await checkFollowingStatus(user.id);
              return { ...user, isFollowing };
            }
          })
        );
        
        setMutualFollows(usersWithFollowStatus);
      } else {
        message.error('获取互关列表失败');
        setMutualFollows([]);
        setMutualCount(0);
      }
    } catch (error) {
      console.error('获取互关列表失败:', error);
      message.error('网络错误，请检查连接');
      setMutualFollows([]);
      setMutualCount(0);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (visible) {
      fetchMutualFollows();
    }
  }, [visible, userId]);

  // 处理头像URL
  const processAvatarUrl = (avatar: string | undefined): string => {
    if (!avatar || avatar === 'null' || avatar === 'undefined' || avatar === '') {
      return '';
    }
    
    if (avatar.startsWith('http')) {
      return avatar;
    }
    
    if (avatar.startsWith('/')) {
      return `http://218.244.141.86:8080${avatar}`;
    } else {
      return `http://218.244.141.86:8080/${avatar}`;
    }
  };

  // 跳转到用户页面
  const handleUserClick = (user: User) => {
    if (user && user.id) {
      onClose();
      setTimeout(() => {
        navigate(`/user/${user.id}`);
      }, 100);
    } else {
      message.error('用户ID无效');
    }
  };

  return (
    <Modal
      title={`互相关注 (${mutualCount})`}
      open={visible}
      onCancel={onClose}
      footer={null}
      width={450}
      style={{ top: 20 }}
      styles={{
        content: { backgroundColor: '#fdf6e9', borderRadius: '12px' },
        body: { backgroundColor: '#fdf6e9', padding: '20px', borderRadius: '12px', maxHeight: '60vh', overflow: 'auto' },
        header: { backgroundColor: '#fdf6e9', borderBottom: '1px solid #e8d5b5', borderRadius: '12px 12px 0 0' }
      }}
    >
      {loading ? (
        <div style={{ textAlign: 'center', padding: '40px' }}>
          <Spin />
          <div style={{ marginTop: 10, color: '#8b4513' }}>加载互关列表...</div>
        </div>
      ) : mutualFollows.length > 0 ? (
        <List
          dataSource={mutualFollows}
          renderItem={(user, index) => (
            <List.Item 
              style={{ 
                borderBottom: '1px solid #f0f0f0', 
                padding: '12px 0',
              }}
            >
              <div style={{ 
                display: 'flex', 
                alignItems: 'center', 
                gap: '12px', 
                width: '100%',
                transition: 'all 0.3s ease'
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.transform = 'translateX(5px)';
                e.currentTarget.style.backgroundColor = 'rgba(240,224,208,0.3)';
                e.currentTarget.style.borderRadius = '8px';
                e.currentTarget.style.padding = '8px';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.transform = 'translateX(0)';
                e.currentTarget.style.backgroundColor = 'transparent';
                e.currentTarget.style.padding = '0';
              }}
              >
                <Avatar 
                  size={40} 
                  src={user.avatar ? processAvatarUrl(user.avatar) : undefined}
                  icon={<UserOutlined />}
                  style={{ backgroundColor: '#e8d9c7', cursor: 'pointer' }}
                  onError={() => false}
                  onClick={() => handleUserClick(user)}
                />
                <div 
                  style={{ flex: 1, cursor: 'pointer' }}
                  onClick={() => handleUserClick(user)}
                >
                  <Text strong style={{ color: '#8b4513', display: 'block', fontSize: '14px' }}>
                    {user.nickname}
                  </Text>
                  <Text type="secondary" style={{ fontSize: '12px' }}>
                    @{user.username}
                  </Text>
                  {user.bio && (
                    <Text type="secondary" style={{ fontSize: '11px', display: 'block', marginTop: '2px', lineHeight: '1.2' }}>
                      {user.bio}
                    </Text>
                  )}
                </div>
                
                {/* 关注按钮 - 只在查看他人互关列表且不是自己时显示 */}
                {!isCurrentUser && (
                  <Button
                    type={user.isFollowing ? "default" : "primary"}
                    icon={user.isFollowing ? <CheckOutlined /> : <PlusOutlined />}
                    loading={followLoading === user.id}
                    size="small"
                    style={{
                      borderRadius: '16px',
                      backgroundColor: user.isFollowing ? '#f0f0f0' : '#e8d9c7',
                      borderColor: user.isFollowing ? '#d9d9d9' : '#e8d9c7',
                      color: user.isFollowing ? '#666' : '#8b4513',
                      fontSize: '12px',
                      minWidth: '70px'
                    }}
                    onClick={(e) => {
                      e.stopPropagation();
                      handleFollowAction(user, index);
                    }}
                  >
                    {user.isFollowing ? '已关注' : '关注'}
                  </Button>
                )}
              </div>
            </List.Item>
          )}
          locale={{ emptyText: '暂无互相关注的用户' }}
        />
      ) : (
        <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
          暂无互相关注的用户
        </div>
      )}
    </Modal>
  );
}

export default Mutualfollowing;